#include <stdlib.h>
#include <stdio.h>
#include <nds.h>

// common headers
#include "common.h"

// local headers

#include "main.h"

#define _VERSION_INT MAKE_VERSION(0, 0, 1, STATE_ALPHA, 1)
char _VERSION_STR[VERSION_STR_MAX_LEN+1];

// libraries id (zero terminated array)
u32 ids[]={ ID_LIBRARY_PICTURE, 0 };

int init() {
	std->sprintf(_VERSION_STR, VERSION_FORMAT, VERSION_ARGS(_VERSION_INT));	// make version str

	return 0;
}

u32 query(u32 query) {
	switch(query) {
	case QUERY_NAME:		// plugin name
		return (u32)"picture viewer";
	case QUERY_VERSION_INT:	// plugin integer version
		return (u32)_VERSION_INT;
	case QUERY_VERSION_STR:	// plugin string version
		return (u32)_VERSION_STR;
	case QUERY_AUTHOR:		// plugin author
		return (u32)"Ludo6431";
	case QUERY_IDS:			// libraries id (zero terminated array)
		return (u32)ids;
	case QUERY_FILEEXT:		// file extensions directly handled by the plugin
		return (u32)NULL;
	default:
		return 0;
	}
}

int main(int argc, char *argv[]) {
    sLibResult libres;
    sLibProc *libpic;
    sPInterface *PI;

	std->iprintf("\x1b[2J");

	if(argc!=1) {
		std->iprintf("Usage:\n\t<image file>\n");
		return 1;
	}

	libpic=api->newLibInstance((libres=api->getLibraryByFileExt(argv[0], tPICTURE)).lib);
	if(!libpic) {
		std->iprintf("Can't open library for image \"%s\"\n", x->basename(argv[0]));
		return 1;
	}

	PI=(sPInterface *)libpic->query(QUERY_FSTRUCT);
	if(!PI) {
		std->iprintf("Invalid picture library \"%s\"\n", libpic->parent->name);
		api->deleteLibInstance(libpic);
		return 1;
	}

	FILE *fd=f->open(argv[0], "rb+");
	if(!fd) {
		std->iprintf("Can't open picture \"%s\"\n", argv[0]);
		api->deleteLibInstance(libpic);
		return 1;
	}

	// TODO : use PI->decode

	f->close(fd);
	api->deleteLibInstance(libpic);

	return 0;
}

void deinit() {
}

